package com.jnu.myAccount;


import android.annotation.SuppressLint;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import androidx.lifecycle.MutableLiveData;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyTextInputWatcher implements TextWatcher {

    private final EditText editText;
    private final MutableLiveData<String> fund;

    public MyTextInputWatcher(EditText editText, MutableLiveData<String> fund)
    {
        super();
        this.editText=editText;
        this.fund = fund;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
//        int selectionStart = editText.getSelectionStart();
//        int selectionEnd = editText.getSelectionEnd();
//
//        //判断是否为纯数字
//        if (!isOnlyPointNumber(editText.getText().toString())){
//            //非数字则删除
//            if(s.length()>=1)
//            {
//                s.delete(selectionStart - 1, selectionEnd);
//            }
//        }
        if(fund!=null)
        {
            fund.postValue(s.toString());
        }
    }

    //判断是否为纯数字
    private boolean isOnlyPointNumber(String number)
    {
        Pattern pattern = Pattern.compile("^\\d+\\.?\\d{0,2}$");
        Matcher matcher = pattern.matcher(number);
        return matcher.matches();
    }

    //获取标准float字符串
    @SuppressLint("DefaultLocale")
    public static String getStandardFloatString(Float num)
    {
        return String.format("%.2f",num).replace("\n","");
    }

    //获取标准date字符串
    public static  String getStandardDateString(Date date)
    {
        return String.format("%tF%n",date).replace("\n","");
    }

    //获取标准当月初始日期以及结束日期
    public static String[] getDateRange(int year,int month)
    {
        int firstDay = 1,lastDay=0;
        String[] dateRange= new String[2];
        switch  (month) {
            case  1 :
            case  3 :
            case  5 :
            case  7 :
            case  8 :
            case  10 :
            case  12 :
                lastDay=31;
                break ;
            case  4 :
            case  6 :
            case  9 :
            case  11 :
                lastDay=30;
                break;
            case  2 :
                if  (year% 4 == 0  && year% 100 != 0  || year% 400 == 0 ) {
                    lastDay =  29 ;
                } else  {
                    lastDay =  28 ;
                }
                break ;
            default :
                break ;
        }

        dateRange[0] = year+"-"+month+"-"+0+firstDay;
        dateRange[1] = year+"-"+month+"-"+lastDay;

        return dateRange;
    }

}
